package com.bsoft.gol.hcs.specialist.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ctd.controller.exception.ControllerException;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.util.ResultCode;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.bsoft.gol.hcs.specialist.bean.request.SyncAnswerListRequest;
import com.bsoft.gol.hcs.specialist.bean.response.AnswerDiagnosis;
import com.bsoft.gol.hcs.specialist.bean.response.SyncAnswerListResponse;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.*;
import com.bsoft.gol.hcs.specialist.service.IFollowUpAnswerService;
import com.bsoft.gol.hcs.utils.CommonUtils;
import com.bsoft.gol.hcs.utils.Constants;


import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author tongtp
 * @version v0.1
 * @className FollowUpAnswerServiceImpl
 * @description 随访表单答题情况服务
 * @create 2020-07-31 14:47
 **/
@SsdevService("followUpAnswerService")
public class FollowUpAnswerServiceImpl implements IFollowUpAnswerService {

    private final static Logger logger = LoggerFactory.getLogger(FollowUpAnswerServiceImpl.class);
    private final ConcurrentHashMap<String, Integer> failReportIdMap = new ConcurrentHashMap<>();
    @Autowired
    private FusAnswerCheckReportInfoDAO fusAnswerCheckReportInfoDAO;
    @Autowired
    private FusAnswerDiagnosisInfoDAO fusAnswerDiagnosisInfoDAO;
    @Autowired
    private FusAnswerInHospitalInfoDAO fusAnswerInHospitalInfoDAO;
    @Autowired
    private FusAnswerInspectionReportInfoDAO fusAnswerInspectionReportInfoDAO;
    @Autowired
    private FusAnswerOperativeInfoDAO fusAnswerOperativeInfoDAO;
    @Autowired
    private FusAnswerOutpatientInfoDAO fusAnswerOutpatientInfoDAO;
    @Autowired
    private FusAnswerDrugInfoDAO fusAnswerDrugInfoDAO;
    @Autowired
    private FollowUpRecordsDAO followUpRecordsDAO;
    @Autowired
    private FusAnswerTreatmentInfoDAO fusAnswerTreatmentInfoDAO;
    @Autowired
    private FusCrucialIndexRecordDAO fusCrucialIndexRecordDAO;

    /**
     * @throws
     * @description: 自动更新指标结果内容
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/7/31 14:45
     */
    @Override
    @RpcService
    public void autoUpdateIndexResultContent() {
        //目前只更新30天内填写的指标，太久远的数据不再处理
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR, -30);
        Date answerTime = instance.getTime();
        //更新检查报告指标结果内容
        Integer updateCount = fusAnswerCheckReportInfoDAO.updateIndexResultContent(answerTime);
        logger.info("更新检查报告指标结果内容数目：{}", updateCount);
        //更新检验报告指标结果内容
        updateCount = fusAnswerInspectionReportInfoDAO.updateIndexResultContent(answerTime);
        logger.info("更新检验报告指标结果内容数目：{}", updateCount);
        return;
    }

    /**
     * @throws
     * @description: 同步表单编辑器答案
     * @return: org.atag.core.base.BaseResponse
     * @author: tongtp
     * @date: 2020/8/3 9:42
     */
    @Override
    @RpcService
    public void syncEditorAnswer() throws ControllerException {
        //目前暂定每次同步200条
        Integer maxSize = 400;
        //接口同步数量
        Long syncCount = 0L;
        //同步失败数量
        Long failCount = 0L;
        //重试次数
        Integer retryCount = 0;
        //获取待同步的答案列表
        SyncAnswerListRequest syncAnswerListRequest = new SyncAnswerListRequest();
        syncAnswerListRequest.setMaxSize(maxSize);
        JSONObject syncJSONParams = JSONObject.parseObject(JSONObject.toJSONString(syncAnswerListRequest));
        String syncUrl = Constants.EDITOR_FOLLOW_UP + Constants.SYNC_ANSWER_LIST;
        String confirmUrl = Constants.EDITOR_FOLLOW_UP + Constants.SYNC_ANSWER_CONFIRM;
        List<SyncAnswerListResponse> syncAnswerLists;
        while (true) {
            //获取待同步的答案列表
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(syncUrl, syncJSONParams);
            logger.info("获取待同步的答案列表返回值json:{}", jsonObject.toJSONString());
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
                syncAnswerLists = JSONObject.parseArray(
                        jsonObject.get("data").toString(), SyncAnswerListResponse.class);
                if (!CollectionUtils.isEmpty(syncAnswerLists)) {
                    syncCount += syncAnswerLists.size();
                    //确认同步成功的记录id集合
                    JSONArray reportIds = new JSONArray();
                    FollowUpRecords followUpRecords;
                    Date now = new Date();

                    for (SyncAnswerListResponse syncAnswerListResponse : syncAnswerLists) {
                        if (CommonUtils.isNotEmpty(syncAnswerListResponse.getReportContent())) {
                            syncAnswerListResponse = JSONObject.parseObject(syncAnswerListResponse.getReportContent(), SyncAnswerListResponse.class);
                        }
                        String userInfoId = syncAnswerListResponse.getUserInfoId();
                        String titleId = syncAnswerListResponse.getTitleId();
                        if (StringUtils.hasText(syncAnswerListResponse.getReportId()) && StringUtils.hasText(userInfoId)
                                && StringUtils.hasText(titleId) && syncAnswerListResponse.getAnswerTime() != null
                                && syncAnswerListResponse.getSubassemblyType() != null) {
                            followUpRecords =
                                    followUpRecordsDAO.getByUserInfoId(userInfoId);
                            if (followUpRecords == null) {
                                logger.info("同步表单编辑器答案问卷答案Id无法识别，无法关联到对应的随访记录：{}", syncAnswerListResponse);
                                handleFailReportIdMap(reportIds, syncAnswerListResponse);
                                failCount++;
                                continue;
                            }

                            try {
                                //控件类型：1、检查报告控件 2、检验报告控件 3、门诊记录控件 4、住院记录控件 5、手术记录控件
                                switch (syncAnswerListResponse.getSubassemblyType()) {
                                    case 1:
                                        //保存检查报告答案信息
                                        saveFusAnswerCheckReportInfo(reportIds, followUpRecords, now,
                                                syncAnswerListResponse, userInfoId, titleId);
                                        break;
                                    case 2:
                                        //保存检验报告答案信息
                                        saveFusAnswerInspectionReportInfo(reportIds, followUpRecords, now,
                                                syncAnswerListResponse, userInfoId, titleId);
                                        break;
                                    case 3:
                                        //保存门诊记录答案信息
                                        saveFusAnswerOutpatientInfo(reportIds, followUpRecords, now,
                                                syncAnswerListResponse, userInfoId, titleId);
                                        break;
                                    case 4:
                                        //保存住院记录答案信息
                                        saveFusAnswerInHospitalInfo(reportIds, followUpRecords, now,
                                                syncAnswerListResponse, userInfoId, titleId);
                                        break;
                                    case 5://
                                        //保存手术记录答案信息
                                        saveFusAnswerOperativeInfo(reportIds, followUpRecords, now, syncAnswerListResponse
                                                , userInfoId, titleId);
                                        break;
                                    case 8://
                                        //保存用药记录答案信息
                                        saveFusAnswerDrugInfo(reportIds, followUpRecords, now, syncAnswerListResponse
                                                , userInfoId, titleId);
                                        break;
                                    case 9://
                                        //保存门诊处置答案信息
                                        saveFusAnswerTreatmentInfo(reportIds, followUpRecords, now, syncAnswerListResponse
                                                , userInfoId, titleId);
                                        break;
                                    default:
                                        handleFailReportIdMap(reportIds, syncAnswerListResponse);
                                        logger.info("同步表单编辑器答案控件类型无法识别，跳过处理，数据：{}", syncAnswerListResponse);
                                        failCount++;
                                        break;
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        } else {
                            logger.info("同步表单编辑器答案数据字段不全，跳过处理，数据：{}", syncAnswerListResponse);
                            if (StringUtils.hasText(syncAnswerListResponse.getReportId())) {
                                handleFailReportIdMap(reportIds, syncAnswerListResponse);
                            } else {
                                logger.info("存在表单编辑器答案数据的reportId为空，停止同步表单编辑器答案");
                                throw new ControllerException("存在表单编辑器答案数据的reportId为空，停止同步表单编辑器答案");
//								return BaseRespUtil.setResultSuccess("存在表单编辑器答案数据的reportId为空，停止同步表单编辑器答案");
                            }
                            failCount++;
                        }
                    }
                    if (!CollectionUtils.isEmpty(reportIds)) {
                        //确认答案同步结果
                        KdHttpClientUtil.doPostJSONArrayRequest(confirmUrl, reportIds);
                    }
                }
            } else {
                logger.info("同步表单编辑器答案失败或者数据为空，接口返回结果：{}", jsonObject);
                retryCount++;
            }
            if (retryCount > 2) {
                logger.info("同步表单编辑器答案,接口同步数据条数:{},同步失败数据条数:{},最后一次接口返回接口结果:{}", syncCount, failCount, jsonObject);
                return;
//				return BaseRespUtil.setResultSuccess("同步表单编辑器答案,接口同步数据条数:{" + syncCount + "},同步失败数据条数:{" + failCount + "}," +
//						"最后一次接口返回结果:{" + jsonObject.toJSONString() + "}");
            }
        }
    }

    /**
     * @param reportIds
     * @param syncAnswerListResponse
     * @throws
     * @description: 处理维护FailReportIdMap
     * @return: void
     * @author: tongtp
     * @date: 2020/8/26 11:00
     */
    private void handleFailReportIdMap(JSONArray reportIds, SyncAnswerListResponse syncAnswerListResponse) {
        if (failReportIdMap.get(syncAnswerListResponse.getReportId()) == null) {
            failReportIdMap.put(syncAnswerListResponse.getReportId(), 1);
        } else if (failReportIdMap.get(syncAnswerListResponse.getReportId()) > 9) {
            reportIds.add(syncAnswerListResponse.getReportId());
            failReportIdMap.remove(syncAnswerListResponse.getReportId());
        } else {
            failReportIdMap.put(syncAnswerListResponse.getReportId(),
                    failReportIdMap.get(syncAnswerListResponse.getReportId()) + 1);
        }
    }

    /**
     * @param reportIds
     * @param followUpRecords
     * @param now
     * @param syncAnswerListResponse
     * @param userInfoId
     * @param titleId
     * @throws
     * @description: 保存手术记录答案信息
     * @return: void
     * @author: tongtp
     * @date: 2020/8/6 17:06
     */
    private void saveFusAnswerOperativeInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                            SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                            String titleId) {
        if (StringUtils.hasText(syncAnswerListResponse.getOperativeCode()) && syncAnswerListResponse.getOperativeTime() != null) {
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作
            FusAnswerOperativeInfo fusAnswerOperativeInfo =
                    fusAnswerOperativeInfoDAO.getByReportId(syncAnswerListResponse.getReportId());
            if (fusAnswerOperativeInfo == null) {
                fusAnswerOperativeInfo = new FusAnswerOperativeInfo();
            }
            fusAnswerOperativeInfo.setUserInfoId(userInfoId);
            fusAnswerOperativeInfo.setTitleId(titleId);
            fusAnswerOperativeInfo.setCreateTime(now);
            fusAnswerOperativeInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerOperativeInfo.setCardType(followUpRecords.getCardType());
            fusAnswerOperativeInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerOperativeInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerOperativeInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerOperativeInfo.setDepartmentId(syncAnswerListResponse.getDepartmentId());
            fusAnswerOperativeInfo.setDepartmentName(syncAnswerListResponse.getDepartmentName());
            fusAnswerOperativeInfo.setOperativeCode(syncAnswerListResponse.getOperativeCode());
            fusAnswerOperativeInfo.setOperativeName(syncAnswerListResponse.getOperativeName());
            fusAnswerOperativeInfo.setOperativeRecordId(syncAnswerListResponse.getOperativeRecordId());
            fusAnswerOperativeInfo.setOperativeTime(syncAnswerListResponse.getOperativeTime());
            fusAnswerOperativeInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerOperativeInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerOperativeInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerOperativeInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerOperativeInfo.setAnesthesiaWayCode(syncAnswerListResponse.getAnesthesiaWayCode());
            fusAnswerOperativeInfo.setAnesthesiaWayName(syncAnswerListResponse.getAnesthesiaWayName());
            fusAnswerOperativeInfo.setNotchGrade(syncAnswerListResponse.getNotchGrade());
            fusAnswerOperativeInfo.setHealingGrade(syncAnswerListResponse.getHealingGrade());
            if (CommonUtils.isNull(fusAnswerOperativeInfo.getFusAnswerOperativeInfoId())) {
                fusAnswerOperativeInfoDAO.save(fusAnswerOperativeInfo);
            } else {
                fusAnswerOperativeInfoDAO.update(fusAnswerOperativeInfo);
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @param reportIds
     * @param followUpRecords
     * @param now
     * @param syncAnswerListResponse
     * @param userInfoId
     * @param titleId
     * @throws
     * @description: 保存住院记录答案信息
     * @return: void
     * @author: tongtp
     * @date: 2020/8/6 17:06
     */
    private void saveFusAnswerInHospitalInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                             SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                             String titleId) {
        if (syncAnswerListResponse.getBeAdmissionTime() != null) {
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作
            FusAnswerInHospitalInfo fusAnswerInHospitalInfo =
                    fusAnswerInHospitalInfoDAO.getByReportId(syncAnswerListResponse.getReportId());
            if (fusAnswerInHospitalInfo == null) {
                fusAnswerInHospitalInfo = new FusAnswerInHospitalInfo();
            }
            fusAnswerInHospitalInfo.setUserInfoId(userInfoId);
            fusAnswerInHospitalInfo.setTitleId(titleId);
            fusAnswerInHospitalInfo.setCreateTime(now);
            fusAnswerInHospitalInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerInHospitalInfo.setCardType(followUpRecords.getCardType());
            fusAnswerInHospitalInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerInHospitalInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerInHospitalInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerInHospitalInfo.setBeAdmissionTime(syncAnswerListResponse.getBeAdmissionTime());
            fusAnswerInHospitalInfo.setDischargeTime(syncAnswerListResponse.getDischargeTime());
            fusAnswerInHospitalInfo.setDepartmentId(syncAnswerListResponse.getDepartmentId());
            fusAnswerInHospitalInfo.setDepartmentName(syncAnswerListResponse.getDepartmentName());
            fusAnswerInHospitalInfo.setDoctorId(syncAnswerListResponse.getDoctorId());
            fusAnswerInHospitalInfo.setDoctorName(syncAnswerListResponse.getDoctorName());
            fusAnswerInHospitalInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerInHospitalInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerInHospitalInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerInHospitalInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerInHospitalInfo.setOrganizationId(syncAnswerListResponse.getReportId());
            fusAnswerInHospitalInfo.setOrganizationName(syncAnswerListResponse.getReportId());
            if (CommonUtils.isNull(fusAnswerInHospitalInfo.getFusAnswerInHospitalInfoId())) {
                fusAnswerInHospitalInfoDAO.save(fusAnswerInHospitalInfo);
            } else {
                fusAnswerInHospitalInfoDAO.update(fusAnswerInHospitalInfo);
            }
            if (!CollectionUtils.isEmpty(syncAnswerListResponse.getDiagnosisList())) {
                //保存对应的诊断列表
                for (AnswerDiagnosis answerDiagnosis :
                        syncAnswerListResponse.getDiagnosisList()) {
                    if (StringUtils.hasText(answerDiagnosis.getDiagnosisId()) && answerDiagnosis.getDiagnosisType() != null) {
                        FusAnswerDiagnosisInfo fusAnswerDiagnosisInfo =
                                fusAnswerDiagnosisInfoDAO.getByReportIdAndDiagnosisId(syncAnswerListResponse.getReportId(), answerDiagnosis.getDiagnosisId());
                        if (fusAnswerDiagnosisInfo == null) {
                            fusAnswerDiagnosisInfo = new FusAnswerDiagnosisInfo();
                        }
                        fusAnswerDiagnosisInfo.setUserInfoId(userInfoId);
                        fusAnswerDiagnosisInfo.setTitleId(titleId);
                        fusAnswerDiagnosisInfo.setCreateTime(now);
                        fusAnswerDiagnosisInfo.setPatientId(followUpRecords.getPatientId());
                        fusAnswerDiagnosisInfo.setCardType(followUpRecords.getCardType());
                        fusAnswerDiagnosisInfo.setCardNumber(followUpRecords.getCardNumber());
                        fusAnswerDiagnosisInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
                        fusAnswerDiagnosisInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
                        fusAnswerDiagnosisInfo.setSubassemblyType(syncAnswerListResponse.getSubassemblyType().byteValue());
                        fusAnswerDiagnosisInfo.setDiagnosisId(answerDiagnosis.getDiagnosisId());
                        fusAnswerDiagnosisInfo.setDiagnosisName(answerDiagnosis.getDiagnosisName());
                        //诊断类型：1入院诊断、2出院诊断、3门诊诊断、5其他诊断
                        fusAnswerDiagnosisInfo.setDiagnosisType(answerDiagnosis.getDiagnosisType());
                        fusAnswerDiagnosisInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
                        fusAnswerDiagnosisInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
                        fusAnswerDiagnosisInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
                        fusAnswerDiagnosisInfo.setReportId(syncAnswerListResponse.getReportId());
                        if (CommonUtils.isNull(fusAnswerDiagnosisInfo.getFusAnswerDiagnosisInfoId())) {
                            fusAnswerDiagnosisInfoDAO.save(fusAnswerDiagnosisInfo);
                        } else {
                            fusAnswerDiagnosisInfoDAO.update(fusAnswerDiagnosisInfo);
                        }
                    } else {
                        logger.info("同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，主数据：{},诊断：{}",
                                syncAnswerListResponse.getSubassemblyType(),
                                syncAnswerListResponse, answerDiagnosis);
                    }
                }
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @param reportIds
     * @param followUpRecords
     * @param now
     * @param syncAnswerListResponse
     * @param userInfoId
     * @param titleId
     * @throws
     * @description: 保存门诊记录答案信息
     * @return: void
     * @author: tongtp
     * @date: 2020/8/6 17:06
     */
    private void saveFusAnswerOutpatientInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                             SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                             String titleId) {
        if (syncAnswerListResponse.getVisitTime() != null) {
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作
            FusAnswerOutpatientInfo fusAnswerOutpatientInfo =
                    fusAnswerOutpatientInfoDAO.getByReportId(syncAnswerListResponse.getReportId());
            if (fusAnswerOutpatientInfo == null) {
                fusAnswerOutpatientInfo = new FusAnswerOutpatientInfo();
            }
            fusAnswerOutpatientInfo.setUserInfoId(userInfoId);
            fusAnswerOutpatientInfo.setTitleId(titleId);
            fusAnswerOutpatientInfo.setCreateTime(now);
            fusAnswerOutpatientInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerOutpatientInfo.setCardType(followUpRecords.getCardType());
            fusAnswerOutpatientInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerOutpatientInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerOutpatientInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerOutpatientInfo.setVisitTime(syncAnswerListResponse.getVisitTime());
            fusAnswerOutpatientInfo.setDepartmentId(syncAnswerListResponse.getDepartmentId());
            fusAnswerOutpatientInfo.setDepartmentName(syncAnswerListResponse.getDepartmentName());
            fusAnswerOutpatientInfo.setDoctorId(syncAnswerListResponse.getDoctorId());
            fusAnswerOutpatientInfo.setDoctorName(syncAnswerListResponse.getDoctorName());
            fusAnswerOutpatientInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerOutpatientInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerOutpatientInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerOutpatientInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerOutpatientInfo.setOrganizationId(syncAnswerListResponse.getOrganizationId());
            fusAnswerOutpatientInfo.setOrganizationName(syncAnswerListResponse.getOrganizationName());
            if (CommonUtils.isNull(fusAnswerOutpatientInfo.getFusAnswerOutpatientInfoId())) {
                fusAnswerOutpatientInfoDAO.save(fusAnswerOutpatientInfo);
            } else {
                fusAnswerOutpatientInfoDAO.update(fusAnswerOutpatientInfo);
            }
            if (!CollectionUtils.isEmpty(syncAnswerListResponse.getDiagnosisList())) {
                //保存对应的诊断列表
                for (AnswerDiagnosis answerDiagnosis :
                        syncAnswerListResponse.getDiagnosisList()) {
                    if (StringUtils.hasText(answerDiagnosis.getDiagnosisId())) {
                        FusAnswerDiagnosisInfo fusAnswerDiagnosisInfo =
                                fusAnswerDiagnosisInfoDAO.getByReportIdAndDiagnosisId(syncAnswerListResponse.getReportId(), answerDiagnosis.getDiagnosisId());
                        if (fusAnswerDiagnosisInfo == null) {
                            fusAnswerDiagnosisInfo = new FusAnswerDiagnosisInfo();
                        }
                        fusAnswerDiagnosisInfo.setUserInfoId(userInfoId);
                        fusAnswerDiagnosisInfo.setTitleId(titleId);
                        fusAnswerDiagnosisInfo.setCreateTime(now);
                        fusAnswerDiagnosisInfo.setPatientId(followUpRecords.getPatientId());
                        fusAnswerDiagnosisInfo.setCardType(followUpRecords.getCardType());
                        fusAnswerDiagnosisInfo.setCardNumber(followUpRecords.getCardNumber());
                        fusAnswerDiagnosisInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
                        fusAnswerDiagnosisInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
                        fusAnswerDiagnosisInfo.setSubassemblyType(syncAnswerListResponse.getSubassemblyType().byteValue());
                        fusAnswerDiagnosisInfo.setDiagnosisId(answerDiagnosis.getDiagnosisId());
                        fusAnswerDiagnosisInfo.setDiagnosisName(answerDiagnosis.getDiagnosisName());
                        //诊断类型：1入院诊断、2出院诊断、3门诊诊断、5其他诊断
                        fusAnswerDiagnosisInfo.setDiagnosisType((byte) 3);
                        fusAnswerDiagnosisInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
                        fusAnswerDiagnosisInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
                        fusAnswerDiagnosisInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
                        fusAnswerDiagnosisInfo.setReportId(syncAnswerListResponse.getReportId());
                        if (CommonUtils.isNull(fusAnswerDiagnosisInfo.getFusAnswerDiagnosisInfoId())) {
                            fusAnswerDiagnosisInfoDAO.save(fusAnswerDiagnosisInfo);
                        } else {
                            fusAnswerDiagnosisInfoDAO.update(fusAnswerDiagnosisInfo);
                        }
                    } else {
                        logger.info("同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，主数据：{},诊断：{}",
                                syncAnswerListResponse.getSubassemblyType(),
                                syncAnswerListResponse, answerDiagnosis);
                    }
                }
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @param reportIds
     * @param followUpRecords
     * @param now
     * @param syncAnswerListResponse
     * @param userInfoId
     * @param titleId
     * @throws
     * @description: 保存检验报告答案信息
     * @return: void
     * @author: tongtp
     * @date: 2020/8/6 17:05
     */
    private void saveFusAnswerInspectionReportInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                                   SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                                   String titleId) {
//        if (StringUtils.hasText(syncAnswerListResponse.getItemId()) && StringUtils.hasText(syncAnswerListResponse.getResult())
//                && syncAnswerListResponse.getSampleTestTime() != null) {

        if (CommonUtils.isNotEmpty(syncAnswerListResponse.getItemName())){
        //查询是否已经存在表单编辑器问卷答案，存在进行更新操作
            FusAnswerInspectionReportInfo fusAnswerInspectionReportInfo =
                    fusAnswerInspectionReportInfoDAO.getByReportId(syncAnswerListResponse.getReportId());
            if (fusAnswerInspectionReportInfo == null) {
                fusAnswerInspectionReportInfo = new FusAnswerInspectionReportInfo();
            }
            fusAnswerInspectionReportInfo.setUserInfoId(userInfoId);
            fusAnswerInspectionReportInfo.setTitleId(titleId);
            fusAnswerInspectionReportInfo.setCreateTime(now);
            fusAnswerInspectionReportInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerInspectionReportInfo.setCardType(followUpRecords.getCardType());
            fusAnswerInspectionReportInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerInspectionReportInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerInspectionReportInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerInspectionReportInfo.setItemId(syncAnswerListResponse.getItemId());
            fusAnswerInspectionReportInfo.setItemName(syncAnswerListResponse.getItemName());
            fusAnswerInspectionReportInfo.setResult(syncAnswerListResponse.getResult());
            fusAnswerInspectionReportInfo.setRefRange(syncAnswerListResponse.getRefRange());
            fusAnswerInspectionReportInfo.setResultUnit(syncAnswerListResponse.getResultUnit());
            fusAnswerInspectionReportInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerInspectionReportInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerInspectionReportInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerInspectionReportInfo.setReportTime(syncAnswerListResponse.getReportTime());
            fusAnswerInspectionReportInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerInspectionReportInfo.setSpecimenTypeId(syncAnswerListResponse.getSpecimenTypeId());
            fusAnswerInspectionReportInfo.setSpecimenTypeName(syncAnswerListResponse.getSpecimenTypeName());
            fusAnswerInspectionReportInfo.setSampleTestTime(syncAnswerListResponse.getSampleTestTime());

            //查询问卷答案范围
            Map<String, Object> stringObjectMap = fusCrucialIndexRecordDAO.queryResultMap(fusAnswerInspectionReportInfo.getItemId(), String.valueOf(fusAnswerInspectionReportInfo.getDiseaseTypeId()));
            if (null != stringObjectMap) {
                //结果性质 1 定量 2 阴阳性 3 数量（-+）4 清洁度 5 血型 6 颜色 7 透明度 8 文本
                String indexResultType = (String) stringObjectMap.get("indexResultType");
                if ("1".equals(indexResultType)) {
                    double indexLowerLimit = Double.valueOf(String.valueOf(stringObjectMap.get("indexLowerLimit")));
                    double indexUpperLimit = Double.valueOf(String.valueOf(stringObjectMap.get("indexUpperLimit")));
                    double result = Double.valueOf(String.valueOf(stringObjectMap.get("result")));
                    //结果状态 1正常  2偏高 3 偏低
                    String resultStatus = "1";
                    if (result < indexLowerLimit) {
                        resultStatus = "3";
                    } else if (result > indexUpperLimit) {
                        resultStatus = "2";
                    }
                    fusAnswerInspectionReportInfo.setResultStatus(resultStatus);
                    String refRange = stringObjectMap.get("indexLowerLimit") + "-" + stringObjectMap.get("indexUpperLimit");
                    fusAnswerInspectionReportInfo.setRefRange(refRange);

                    if(!"1".equals(resultStatus) && null != fusAnswerInspectionReportInfo.getUserInfoId()){
                        FollowUpRecords records = followUpRecordsDAO.getFollowUpRecordsByUserInfoId(fusAnswerInspectionReportInfo.getUserInfoId());
                        if(null != records){
                            //异常状态 1是，2否 默认2
                            records.setAnswerAbnormal("1");
                            followUpRecordsDAO.update(records);
                        }
                    }
                }
            }

            fusAnswerInspectionReportInfo.setSampleTestTime(syncAnswerListResponse.getSampleTestTime());
            if (CommonUtils.isNull(fusAnswerInspectionReportInfo.getFusAnswerInspectionReportInfoId())) {
                fusAnswerInspectionReportInfoDAO.save(fusAnswerInspectionReportInfo);
            } else {
                fusAnswerInspectionReportInfoDAO.update(fusAnswerInspectionReportInfo);
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("保存检验报告答案信息,同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @param reportIds
     * @param followUpRecords
     * @param now
     * @param syncAnswerListResponse
     * @param userInfoId
     * @param titleId
     * @throws
     * @description: 保存检查报告答案信息
     * @return: void
     * @author: tongtp
     * @date: 2020/8/6 17:04
     */
    private void saveFusAnswerCheckReportInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                              SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                              String titleId) {
//        if (StringUtils.hasText(syncAnswerListResponse.getItemId()) && StringUtils.hasText(syncAnswerListResponse.getItemContent())
//                && syncAnswerListResponse.getReportTime() != null) {
        //        if (StringUtils.hasText(syncAnswerListResponse.getItemId()) && StringUtils.hasText(syncAnswerListResponse.getItemContent())

        if (CommonUtils.isNotEmpty(syncAnswerListResponse.getItemName())){
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作
            FusAnswerCheckReportInfo fusAnswerCheckReportInfo =
                    fusAnswerCheckReportInfoDAO.getByReportId(syncAnswerListResponse.getReportId());
            if (fusAnswerCheckReportInfo == null) {
                fusAnswerCheckReportInfo = new FusAnswerCheckReportInfo();
            }
            fusAnswerCheckReportInfo.setUserInfoId(userInfoId);
            fusAnswerCheckReportInfo.setTitleId(titleId);
            fusAnswerCheckReportInfo.setCreateTime(now);
            fusAnswerCheckReportInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerCheckReportInfo.setCardType(followUpRecords.getCardType());
            fusAnswerCheckReportInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerCheckReportInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerCheckReportInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerCheckReportInfo.setItemId(syncAnswerListResponse.getItemId());
            fusAnswerCheckReportInfo.setItemName(syncAnswerListResponse.getItemName());
            fusAnswerCheckReportInfo.setItemContent(syncAnswerListResponse.getItemContent());
            fusAnswerCheckReportInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerCheckReportInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerCheckReportInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerCheckReportInfo.setReportTime(syncAnswerListResponse.getReportTime());
            fusAnswerCheckReportInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerCheckReportInfo.setExamTypeCode(syncAnswerListResponse.getExamTypeCode());
            fusAnswerCheckReportInfo.setExamTypeName(syncAnswerListResponse.getExamTypeName());
            fusAnswerCheckReportInfo.setExamPartCode(syncAnswerListResponse.getExamPartCode());
            fusAnswerCheckReportInfo.setExamPartName(syncAnswerListResponse.getExamPartName());
            fusAnswerCheckReportInfo.setExamPhotoId(syncAnswerListResponse.getExamPhotoId());
            fusAnswerCheckReportInfo.setDiagnoseName(syncAnswerListResponse.getDiagnoseName());
            fusAnswerCheckReportInfo.setImageNo(syncAnswerListResponse.getImageNo());
            if (CommonUtils.isNull(fusAnswerCheckReportInfo.getFusAnswerCheckReportInfoId())) {
                fusAnswerCheckReportInfoDAO.save(fusAnswerCheckReportInfo);
            } else {
                fusAnswerCheckReportInfoDAO.update(fusAnswerCheckReportInfo);
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("保存检查报告答案信息，同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @description: 同步处方药品信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/25 19:51
     * @param: reportIds
     * @param: followUpRecords
     * @param: now
     * @param: syncAnswerListResponse
     * @param: userInfoId
     * @param: titleId
     * @return: void
     */
    private void saveFusAnswerDrugInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                       SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                       String titleId) {

        if (StringUtils.hasText(syncAnswerListResponse.getDrugName())) {
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作

            FusAnswerDrugInfo fusAnswerDrugInfo = fusAnswerDrugInfoDAO.getByReportId(syncAnswerListResponse.getReportId());

            if (fusAnswerDrugInfo == null) {
                fusAnswerDrugInfo = new FusAnswerDrugInfo();
            }
            fusAnswerDrugInfo.setUserInfoId(userInfoId);
            fusAnswerDrugInfo.setTitleId(titleId);
            fusAnswerDrugInfo.setCreateTime(now);
            fusAnswerDrugInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerDrugInfo.setCardType(followUpRecords.getCardType());
            fusAnswerDrugInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerDrugInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerDrugInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerDrugInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerDrugInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerDrugInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerDrugInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerDrugInfo.setPrescriptionId("");
            fusAnswerDrugInfo.setDrugsNumber(syncAnswerListResponse.getDrugsNumber());
            fusAnswerDrugInfo.setDrugName(syncAnswerListResponse.getDrugName());
            fusAnswerDrugInfo.setDrugUsePathwaysCode(syncAnswerListResponse.getDrugUsePathwaysCode());
            fusAnswerDrugInfo.setDrugUsePathwaysName(syncAnswerListResponse.getDrugUsePathwaysName());
            fusAnswerDrugInfo.setDrugUsingRate(syncAnswerListResponse.getDrugUsingRate());
            fusAnswerDrugInfo.setDrugUsingRateName(syncAnswerListResponse.getDrugUsingRateName());
            fusAnswerDrugInfo.setOnceDosage(syncAnswerListResponse.getOnceDosage());
            fusAnswerDrugInfo.setDosageUnit(syncAnswerListResponse.getDosageUnit());
            fusAnswerDrugInfo.setMedicineDays(syncAnswerListResponse.getMedicineDays() == null ? 0 : Integer.valueOf(syncAnswerListResponse.getMedicineDays()));
            fusAnswerDrugInfo.setDrugSendNumber(syncAnswerListResponse.getDrugSendNumber());
            fusAnswerDrugInfo.setPrice(new BigDecimal("0"));
            fusAnswerDrugInfo.setDrugstoreUnit(syncAnswerListResponse.getDrugstoreUnit());
            fusAnswerDrugInfo.setDrugSpecifications(syncAnswerListResponse.getDrugSpecifications());
            fusAnswerDrugInfo.setAnswerTime(new Date());

            if (CommonUtils.isNull(fusAnswerDrugInfo.getFusAnswerDrugInfoId())) {
                fusAnswerDrugInfoDAO.save(fusAnswerDrugInfo);
            } else {
                fusAnswerDrugInfoDAO.update(fusAnswerDrugInfo);
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("同步处方药品信息，同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }

    /**
     * @description: 保存处置记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/10/25 20:01
     * @param: reportIds
     * @param: followUpRecords
     * @param: now
     * @param: syncAnswerListResponse
     * @param: userInfoId
     * @param: titleId
     * @return: void
     */
    private void saveFusAnswerTreatmentInfo(JSONArray reportIds, FollowUpRecords followUpRecords, Date now,
                                            SyncAnswerListResponse syncAnswerListResponse, String userInfoId,
                                            String titleId) {

        if (CommonUtils.isNotEmpty(syncAnswerListResponse.getDrugName()) && CommonUtils.isNotEmpty(syncAnswerListResponse.getOperativeTime())) {
            //查询是否已经存在表单编辑器问卷答案，存在进行更新操作

            FusAnswerTreatmentInfo fusAnswerTreatmentInfo = fusAnswerTreatmentInfoDAO.getByReportId(syncAnswerListResponse.getReportId());

            if (fusAnswerTreatmentInfo == null) {
                fusAnswerTreatmentInfo = new FusAnswerTreatmentInfo();
            }
            fusAnswerTreatmentInfo.setUserInfoId(userInfoId);
            fusAnswerTreatmentInfo.setTitleId(titleId);
            fusAnswerTreatmentInfo.setCreateTime(now);
            fusAnswerTreatmentInfo.setPatientId(followUpRecords.getPatientId());
            fusAnswerTreatmentInfo.setCardType(followUpRecords.getCardType());
            fusAnswerTreatmentInfo.setCardNumber(followUpRecords.getCardNumber());
            fusAnswerTreatmentInfo.setPatientMedicalCardType(followUpRecords.getPatientMedicalCardType());
            fusAnswerTreatmentInfo.setPatientMedicalCardNumber(followUpRecords.getPatientMedicalCardNumber());
            fusAnswerTreatmentInfo.setTreatmentCode("");
            fusAnswerTreatmentInfo.setTreatmentName(syncAnswerListResponse.getTreatmentName());
            fusAnswerTreatmentInfo.setTreatmentTime(syncAnswerListResponse.getTreatmentTime());
            fusAnswerTreatmentInfo.setDiseaseTypeId(followUpRecords.getDiseaseTypeId());
            fusAnswerTreatmentInfo.setDiseaseTypeName(followUpRecords.getDiseaseTypeName());
            fusAnswerTreatmentInfo.setAnswerTime(syncAnswerListResponse.getAnswerTime());
            fusAnswerTreatmentInfo.setReportId(syncAnswerListResponse.getReportId());
            fusAnswerTreatmentInfo.setAnswerTime(new Date());

            if (CommonUtils.isNull(fusAnswerTreatmentInfo.getFusAnswerTreatmentInfoId())) {
                fusAnswerTreatmentInfoDAO.save(fusAnswerTreatmentInfo);
            } else {
                fusAnswerTreatmentInfoDAO.update(fusAnswerTreatmentInfo);
            }
            reportIds.add(syncAnswerListResponse.getReportId());
        } else {
            handleFailReportIdMap(reportIds, syncAnswerListResponse);
            logger.info("保存处置记录，同步表单编辑器答案数据字段不全，跳过处理,SubassemblyType:{}，数据：{}",
                    syncAnswerListResponse.getSubassemblyType(), syncAnswerListResponse);
        }
    }
}
